﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Demo.Entity;
using Demo.Helper;
using MetroFramework.Forms;

namespace Demo.Page
{
    public partial class UserForm : MetroForm
    {
        UserHelper helper = new UserHelper("");
        List<User> listuser = new List<User>();

        public UserForm()
        {
            InitializeComponent();
            if (File.Exists("user.pt"))
            {
                listuser = helper.DeserializedUser("user.pt");
            }
            ShowUserList(listuser);
        }

        public void ShowUserList(List<User> listuser)
        {
            dgvManger.DataSource = null;
            dgvManger.DataSource = listuser;
        }

        /// <summary>
        /// 获取用户输入信息
        /// </summary>
        /// <param name="list">用户信息列表</param>
        /// <returns></returns>
        private User GetUser(List<User> list)
        {
            // 重置错误状态标记
            bool hasError = false;

            // 验证用户名（同时检查是否是错误提示文本）
            if (string.IsNullOrEmpty(txtUser.Text))
            {
                txtUser.ForeColor = Color.Red;
                txtUser.Text = "用户名不能为空！";
                hasError = true;
            }

            // 验证密码
            if (string.IsNullOrEmpty(txtPassWord.Text))
            {
                txtPassWord.ForeColor = Color.Red;
                txtPassWord.PasswordChar = '\0';
                txtPassWord.Text = "密码不能为空！";
                hasError = true;
            }

            // 验证确认密码
            if (string.IsNullOrEmpty(txtPassConfirmWord.Text))
            {
                txtPassConfirmWord.ForeColor = Color.Red;
                txtPassConfirmWord.PasswordChar = '\0';
                txtPassConfirmWord.Text = "密码不能为空！";
                hasError = true;
            }

            // 验证下拉框
            if (cmbLevel.SelectedIndex == -1)
            {
                cmbLevel.ForeColor = Color.Red;
                cmbLevel.Text = "请点击下拉框选择权限！";
                hasError = true;
            }

            // 有错误直接返回
            if (hasError)
            {
                return null;
            }

            // 验证密码一致性（新增）
            if (txtPassWord.Text != txtPassConfirmWord.Text)
            {
                txtPassConfirmWord.ForeColor = Color.Red;
                txtPassConfirmWord.Text = "两次密码不一致！";
                return null;
            }

            // 验证用户名是否已存在（新增）
            if (list.Any(u => u.Name == txtUser.Text))
            {
                txtUser.ForeColor = Color.Red;
                txtUser.Text = "该用户名已存在！";
                return null;
            }

            // 生成新用户（确保使用的是用户实际输入，而非错误提示）
            User user = new User();
            // 处理空列表的情况，避免索引越界
            user.Id = list.Count == 0 ? 1 : list[list.Count - 1].Id + 1;
            user.Name = txtUser.Text;
            user.PassWord = txtPassWord.Text;

            // 根据下拉框选择设置权限
            switch (cmbLevel.SelectedIndex)
            {
                case 0:
                    user.Level = Authority.管理员;
                    break;
                case 1:
                    user.Level = Authority.店长;
                    break;
                case 2:
                    user.Level = Authority.店员;
                    break;
                default:
                    return null;
            }

            return user;
        }

        private void SetUser()
        {
            ////展示用户信息之前先重置所有输入框状态
            //ResetInputStyles();
            DataGridViewSelectedRowCollection rowCollection = dgvManger.SelectedRows;
            //下面的判断-->解决dgvManger_RowEnter事件在窗体加载的时候就触发了但是表格里还没有东西
            if (rowCollection.Count == 0)
                return;
            DataGridViewRow row = rowCollection[0];
            txtUser.Text = row.Cells[1].Value.ToString();
            txtPassWord.Text = row.Cells[2].Value.ToString();
            txtPassConfirmWord.Text = row.Cells[2].Value.ToString();
            cmbLevel.Text = row.Cells[3].Value.ToString();
        }

        /// <summary>
        /// 重置所有输入框状态（清除上次错误样式）
        /// </summary>
        private void ResetInputStyles()
        {
            // 恢复用户名框
            txtUser.ForeColor = Color.Black;
            txtUser.Text = "";
            // 恢复密码框
            txtPassWord.ForeColor = Color.Black;
            txtPassWord.PasswordChar = '*';
            txtPassWord.Text = "";
            // 恢复确认密码框
            txtPassConfirmWord.ForeColor = Color.Black;
            txtPassConfirmWord.PasswordChar = '*';
            txtPassConfirmWord.Text = "";
            // 恢复下拉框
            cmbLevel.ForeColor = Color.Black;
            cmbLevel.Text = "";
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            User user = GetUser(listuser);
            if (user != null)
            {
                helper.AddUser("user.pt", listuser, user);
                ShowUserList(listuser);
            }
        }

        private void txtUser_Enter(object sender, EventArgs e)
        {
            txtUser.ForeColor = Color.Black;
            txtUser.Text = "";
        }

        private void txtPassWord_Enter(object sender, EventArgs e)
        {
            txtPassWord.ForeColor = Color.Black;
            txtPassWord.PasswordChar = '*';
            txtPassWord.Text = "";
        }

        private void txtPassConfirmWord_Enter(object sender, EventArgs e)
        {
            txtPassConfirmWord.ForeColor = Color.Black;
            txtPassConfirmWord.PasswordChar = '*';
            txtPassConfirmWord.Text = "";
        }

        private void cmbLevel_Enter(object sender, EventArgs e)
        {
            cmbLevel.ForeColor = Color.Black;
            cmbLevel.Text = "";
        }

        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            // 实际应用最好结合一些判断
            helper.DeleteUser("user.pt", listuser, txtUser.Text);
            ShowUserList(listuser);
        }

        /// <summary>
        /// 让界面加载完成时焦点不在文本框里，避免信息因为txtUser_Enter事件无法显示的问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserForm_Shown(object sender, EventArgs e)
        {
            dgvManger.Focus();
        }

        private void dgvManger_SelectionChanged(object sender, EventArgs e)
        {
            SetUser();
        }
    }
}
